<?php
/**
 * 象山麻将
 * User: Mr z
 * Date: 2017/12/26
 * Time: 10:17
 * 注意 详细积分表使用t_historyscore，不再使用t_score_detailed
 * 象山麻将的game_id=7
 * account_status（自己的游戏状态） 0：已进入   1：围观（同一房间里面，只要不是坐下，都属于围观）  2：坐下 3：发牌    8：游戏结束
 *
*/

/*
 * Alter table t_room  add `cardsinfo` text COMMENT '牌数据'
 * Alter table t_room  add  `windarea` int(1) DEFAULT '1' COMMENT '1：东风圈，2：南风圈，3，西风圈，4北风圈',
 * Alter table t_room  add `overtype` int(1) DEFAULT '0' COMMENT '1:流局，2荒局，3赢局'
 * is_grab   吃碰杠胡选择之一
 * 数据库 t_member表 cards_info 字段更改为text类型
 * total_num   每次胡牌的时候记录所有可以胡牌的次数，
  */
namespace app\game\controller;
use think\Session;
use think\Controller;
use think\Loader;
use think\Db;
use think\Log;
use app\common\model\Member;
class Xiangshan extends Controller {
	private $gamelockfile;
	private $filed='socre';
	public function __construct() {
		parent::__construct();
		//文件锁路径
		define("LOCK_FILE_PATH", ROOT_PATH . "tmp/lock/");
		Loader::import('extend.Game.Xiangshan');
		$this->Xiangshan = new \Xiangshan(array());
	}
	public function Index(){

    }
	public function Test(){
        $dataPost['room_id']=376011;
        $post['data']['room_id']=$dataPost['room_id'];
        $room = $this->RoomIsExist($post);


        if(!$room){
            return $this->ErrorInfo('GameOver','invalid info!');
        }
        if($room['room_status']<3){
            //保存本轮牌局的结束方式
            $o['overtype']=1;
            $o['roomStatus']=3;
            $o['room_status']=3;
            $this->UpdateRoomById($o,$dataPost['room_id']);
        }
        $memberInRoom=$this->GetAllMemeberIdAtRoom($dataPost['room_id']);
        $allReadyMemberInfo=$memberInRoom['allReadyMemberInfo'];
        $all = Db("historyscore")->Field('id,score')->where("room_id ={$dataPost['room_id']}")->find();
        foreach ($allReadyMemberInfo as $key => $val) {
            if(!$all){
                $scorpe = Db("history")->where("room_id ={$dataPost['room_id']} and member_id={$val['id']}")->sum('scorpe');
                $createtime=time();
                $Isql="'{$val['id']}','{$dataPost['room_id']}','{$scorpe}','{$createtime}'";
                $sql = "INSERT INTO t_historyscore (account_id,room_id,score,end_time) VALUES ($Isql)";
                Db::query($sql);
                //扣除奖励对应的积分
                if($scorpe>0){
                    Db('member')->where('id',$val['id'])->setInc($this->filed,abs($scorpe));
                }else{
                    Db('member')->where('id',$val['id'])->setDec($this->filed,abs($scorpe));
                }
            }else{
                $scorpe=$all['score'];
            }
            $zdetails[$key]['nickname']=@base64_decode($val['nickname']);
            $zdetails[$key]['score']=$scorpe;
            $zdetails[$key]['account_id']=$val['id'];
        }
        exit();

        $cards = model('room')->where(['id' =>375967])->field('cardsinfo')->find();
        $cardsinfo=unserialize($cards['cardsinfo']);

        ////配置牌数据
        unset($cardsinfo['playcards'][0]['dapai'][0]);
        $cardsinfo['playcards'][0]['pai'][]=7;
        //unset($cardsinfo['playcards'][2]['pai'][16]);
        //unset($cardsinfo['playcards'][2]['dapai']);
        //$cardsinfo['playcards'][2]['pai'][13]=0;
        $cardsinfo['turn']=0;
        //$cardsinfo['playcards'][1]['pai'][0]=3;
        //$cardsinfo['playcards'][1]['pai'][1]=3;
        //$cardsinfo['playcards'][1]['pai'][2]=3;
        $allcar['cardsinfo']=serialize($cardsinfo);
        $this->UpdateRoomById($allcar,375967);
        $cards = model('room')->where(['id' =>375967])->field('cardsinfo')->find();
        $cardsinfo=unserialize($cards['cardsinfo']);


  print_r($cardsinfo);


		//$this->Xiangshan->mopai(0,1);
        //$f=$this->Xiangshan->getplaycards();
       // print_r($f);
		//print_r($this->Xiangshan->getyupai());
		//$this->Xiangshan->test();
         //$s=Db('member')->find();
        // print_R($s);
        //$this->PlayerShowCard();
//        $return_data['action'][]='angang';
//                    $return_data['action'][]='wgang';
//            $return_data['action'][]='hu';
//        $return_data['action'] = array('chi'=>1);
//        return  json_encode($return_data);

	}
	public function Test1(){

	    //{"room_id":"375693","account_id":5840,"operation":"ShowCard","action":9,"cur_dpai":3,"wintype":2}

        $dataPost=$this->GetPost('PlayerShowCard');
        $dataPost=[
            'room_id'=>375701,              //房间号
            'operation'=>'ShowCard',          //牌操作
            'action'=>2,                 //  操作种类
            'account_id'=>5840,         //  操作者id
            'cur_dpai'=>14,                //操作牌
            'wintype'=>2,                      //胡的种类
        ];

        if(!$dataPost || !$dataPost['room_id']){
            return $this->ErrorInfo('PlayerShowCard','无效信息');
        }
        // 判断房间是否存在
        $room = model('room')->where(array('id' => $dataPost['room_id']))->find();
        if(!$room){
            return $this->ErrorInfo('PlayerShowCard','房间不存在');
        }
        //判断是否是会员
        $member = $this->IsMember($dataPost['account_id'],'id,account_status,online_status,sort,room_id');
        if(!$member){
            return $this->ErrorInfo('PlayerShowCard','无效信息');
        }
        if($member->room_id!=$dataPost['room_id']){
            return $this->ErrorInfo('PlayerShowCard','房间不对');
        }
//        //寻找room里面cards数据
        $cards = model('room')->where(['id' =>$dataPost['room_id']])->field('cardsinfo')->find();
        $cardsinfo=unserialize($cards['cardsinfo']);
print_r($cardsinfo);

        $cardsinfo['playcards'][0]['pai'][]=14;
//        $cardsinfo['playcards'][0]['pai'][]=1;
//        $cardsinfo['playcards'][0]['pai'][]=2;
//        $cardsinfo['playcards'][0]['pai'][]=3;
//        $cardsinfo['playcards'][0]['pai'][]=2;
//        $cardsinfo['playcards'][0]['pai'][]=3;
//        $cardsinfo['playcards'][0]['pai'][]=4;
//        $cardsinfo['playcards'][0]['pai'][]=4;
//        $cardsinfo['playcards'][0]['pai'][]=5;
//        $cardsinfo['playcards'][0]['pai'][]=6;
//        $cardsinfo['playcards'][0]['pai'][]=11;
//        $cardsinfo['playcards'][0]['pai'][]=12;
//        $cardsinfo['playcards'][0]['pai'][]=13;
//        $cardsinfo['playcards'][0]['pai'][]=22;
//        $cardsinfo['playcards'][0]['pai'][]=22;
        ////配置牌数据
//        $cardsinfo['playcards'][0]['pai'][]=4;
//        $cardsinfo['playcards'][0]['pai'][]=5;
//        $cardsinfo['playcards'][0]['pai'][]=6;
//        $cardsinfo['playcards'][0]['pai'][]=7;
//        $cardsinfo['playcards'][0]['pai'][]=7;
//        $cardsinfo['playcards'][0]['pai'][]=7;
  // $cardsinfo['turn']=0;
////        $cardsinfo['act'] = array(5941=>array('chi'),5942=>array('gang','peng'));
////
 $allcar['cardsinfo']=serialize($cardsinfo);
 $this->UpdateRoomById($allcar,$dataPost['room_id']);
//       $cards = model('room')->where(['id' =>$dataPost['room_id']])->field('cardsinfo')->find();
//      $cardsinfo=unserialize($cards['cardsinfo']);
//


        $data['data']['index']=$member->sort-1;
        $data['data']['cur_dpai']=$dataPost['cur_dpai'];
        $data['data']['wintype']=isset($dataPost['wintype'])?$dataPost['wintype']:0;
        $data['data']['account_id']=$dataPost['account_id'];
        $newdata=$this->cpgchecke($dataPost,$cardsinfo);
        if($newdata!=false){
            $dataPost=$newdata;

            $member = $this->IsMember($dataPost['account_id'],'id,account_status,online_status,sort,room_id');
            if(!$member){
                return $this->ErrorInfo('PlayerShowCard','无效信息');
            }
            if($member->room_id!=$dataPost['room_id']){
                return $this->ErrorInfo('PlayerShowCard','房间不对');
            }
            //寻找room里面cards数据
            $cards = model('room')->where(['id' =>$dataPost['room_id']])->field('cardsinfo')->find();
            $cardsinfo=unserialize($cards['cardsinfo']);
            $data['data']['index']=$member->sort-1;
            $data['data']['cur_dpai']=$dataPost['cur_dpai'];
            $data['data']['wintype']=isset($dataPost['wintype'])?$dataPost['wintype']:0;
            $data['data']['account_id']=$dataPost['account_id'];
            $cardsinfo['windarea']=$room->windarea;
            $this->Xiangshan->setallcards($cardsinfo);
            $result=$this->Xiangshan->actionpai($dataPost['action'],$data['data']);
            $result['action']=$dataPost['action'];
            print_R($result);
            exit();


            $canm=1;
        }else{
            $canm=0;
            //$result = ['msg' => '等待其他人操作', 'type' => 1, 'action' =>$dataPost['action']];
            return $this->ErrorInfo('AllGamerInfo','等待其他人操作');
        }
        if($result['type']>0){
            //获得操作结束之后的牌数据，写入room里面
            $allcards= $this->Xiangshan->getallcards();
            $allcar['cardsinfo']=serialize($allcards);
           // $this->UpdateRoomById($allcar,$dataPost['room_id']);
        }else{
            return $this->ErrorInfo('ShowCard',$result['msg']);
        }
        $evpai=$allcards['playcards'];
        /*****.查询同一房间且符合条件的会员id*******/
        $memberInRoom=$this->GetAllMemeberIdAtRoom($dataPost['room_id']);
        $memberIds=$memberInRoom['memberIds'];//在线的
        $allReadyMember=$memberInRoom['allReadyMember'];
        $allReadyMemberInfo=$memberInRoom['allReadyMemberInfo'];   //打牌者
        $weiGuanMemberInfo=$memberInRoom['weiGuanMemberInfo'];   //围观者
        //荒局，只有摸牌已经摸不到的时候，才可以确定是荒局，保存本局的状态，返回排行榜（全部为0），等待客户端请求重新开局
        //荒局，只有摸牌已经摸不到的时候，才可以确定是荒局，保存本局的状态，返回排行榜（全部为0），等待客户端请求重新开局
        if(isset($result['status'])){
            if($result['status']==1){
                $result['type']=1;
                $result['data']=$this->GetHuangMembersScore($dataPost['room_id']);
                //写入本轮积分到表里面
                foreach ($allReadyMemberInfo as $key => $val) {
                    $current_key=$val['sort']-1;
                    $cards=serialize($evpai[$current_key]);
                    $member_id=$val['id'];
                    $room_id = $dataPost['room_id'];
                    $total_num=1;
                    $is_banker=$val['sort']==1?1:0;
                    $niu_count=0;
                    $scorpe=0;
                    $room_time=time();
                    $createtime=time();
                    $Isql="'{$member_id}','{$room_id}','{$total_num}','{$is_banker}','{$cards}','{$niu_count}','{$scorpe}','{$room_time}','{$createtime}'";
                    $sql = "INSERT INTO t_history (member_id,room_id,total_num,is_banker,cards,niu_count,scorpe,room_time,createtime) VALUES ($Isql)";
                    Db::query($sql);
                    $member_id=$val['id'];
                }
                //保存本轮牌局的结束方式
                $o['overtype']=2;
                $this->UpdateRoomById($o,$dataPost['room_id']);

                $result['result']=0;
                $result['action']=10;
                $result['operation'] = "pull_Huangju";
                //$result['wintype'] =array(['三包',15],['清一色',5],['平胡',2]);
                $result['wintype'] =[];
                $result['wincards'] =[];
                $result['winid'] =[];
                $result['loseid'] =[];
                $result['room_id']= $dataPost['room_id'];
                $players=$this->GetOlinePlayerInfo($dataPost['room_id'],'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
                $cards_info=[];
                foreach ($players as $player) {
                    $obj=new \StdClass();
                    $obj->id=$player['id'];
                    $obj->nickname=$player['nickname'];
                    $obj->cards_info=$player['cards_info'];
                    $obj->score=0;
                    $cards_info[]=$obj;
                    unset($obj);
                }
                $result['players']=$cards_info;
                return json_encode($result);

            }


        }
        //赢局，赢牌保存每个会员的积分数据，保存到排行榜，返回排行榜，等待客户端请求重新开局
        if($result['action']==9){
            if($result['type']>0){
                $zdetails[]=array();
                foreach ($allReadyMemberInfo as $key => $val) {
                    $current_key=$val['sort']-1;
                    $member_id=$val['id'];
                    $room_id = $dataPost['room_id'];
                    $total_num=1;
                    $is_banker=$val['sort']==1?1:0;
                    $niu_count=0;
                    $cards='';
                    // $scorpe=$result['score'][$current_key];
                    $scorpe=0;
                    $chip='';
                    $room_time=time();
                    $createtime=time();
                    $Isql="'{$member_id}','{$room_id}','{$total_num}','{$is_banker}','{$cards}','{$niu_count}','{$scorpe}','{$chip}','{$room_time}','{$createtime}'";
                    $sql = "INSERT INTO t_history (member_id,room_id,total_num,is_banker,cards,niu_count,scorpe,chip,room_time,createtime) VALUES ($Isql)";
                    Db::query($sql);
                    //                //扣除奖励对应的积分
                    //                if($scorpe>0){
                    //                    Db('member')->where('id',$member_id)->setInc($this->filed,abs($scorpe));
                    //                }else{
                    //                    Db('member')->where('id',$member_id)->setDec($this->filed,abs($scorpe));
                    //                }
                    //                //更新到总的排行榜
                    //                $all = model("historyscore")->Field('id,score')->where("room_id =$room_id and account_id={$member_id}")->find();
                    //                if($all['id']>0){
                    //                    $data['score']=$all['score']+$scorpe;
                    //                    model("historyscore")->where("id={$all['id']}")->save($data);
                    //                }else{
                    //                    $Isql="'{$member_id}','{$room_id}','{$scorpe}','{$createtime}'";
                    //                    $sql = "INSERT INTO t_historyscore (account_id,room_id,score,end_time) VALUES ($Isql)";
                    //                    Db::query($sql);
                    //                }

                    $zdetails[$key]['nickname']=@base64_decode($val['nickname']);
                    $zdetails[$key]['score']=$scorpe;
                    $zdetails[$key]['account_id']=$val['id'];
                }
                $result['data']=$zdetails;
                $result['limit_time']=5;
                $result['room_id']= $dataPost['room_id'];
                $result['account_id']=$member_id;
                //保存本轮牌局的结束方式
                $o['overtype']=3;
                $this->UpdateRoomById($o,$dataPost['room_id']);
                //保存下轮的庄家，谁赢了谁当庄家



                $this->UpdateMemberById(['is_banker'=>1],$result['account_id']);
                $result['result']=0;
                $result['action']=10;
                $result['operation'] = "pull_Win";
                //$result['wintype'] =array(['三包',15],['清一色',5],['平胡',2]);
                // $result['wintype'] =[];
                //$result['wincards'] =[];
                //$result['winid'] =[];
                //$result['loseid'] =[];
                $result['room_id']= $dataPost['room_id'];
                $players=$this->GetOlinePlayerInfo($dataPost['room_id'],'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
                $cards_info=[];
                foreach ($players as $player) {
                    $obj=new \StdClass();
                    $obj->id=$player['id'];
                    $obj->nickname=$player['nickname'];
                    $obj->cards_info=$player['cards_info'];
                    $obj->score=0;
                    $cards_info[]=$obj;
                    unset($obj);
                }
                $result['players']=$cards_info;
                return json_encode($result);
            }else{
                $result['type']=0;
                $result['msg']='赢牌数据错误';
                return json_encode($result);
            }
        }

        //保存每个会员的牌数据
        $ds=[];
        foreach ($allReadyMemberInfo as $key => $val) {
            $keys=$val['sort']-1;
            $pai=serialize($evpai[$keys]);
            $ds['cards_info']=$pai;
            if($canm>0) $ds['is_grab']=0;
            //$this->UpdateMemberById($ds,$val['id']);
        }
        $players=$this->GetOlinePlayerInfo($dataPost['room_id'],'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
        $cards_info=[];
        foreach ($players as $player) {
            $obj=new \StdClass();
            $obj->id=$player['id'];
            $obj->sort=$player['sort'];
            $obj->nickname=@base64_decode($player['nickname']);
            $obj->photo=$player['photo'];
            $obj->online_status=$player['online_status'];
            $obj->data=$player['cards_info'];
            $obj->isspecial='false';
            $obj->score=$player[$this->filed];
            $cards_info[]=$obj;
            unset($obj);
        }
        //$result['cards_info']=$cards_info;
        $result['players']=$cards_info;
        $result['weiplayers']=$weiGuanMemberInfo;
        $result['room_id']= $dataPost['room_id'];
        $result['account_id']=$dataPost['account_id'];
        $returnData= json_encode($result);
        $returnData = json_decode($returnData);
        print_r($returnData);


    }
	/**
	 * 获取个人信息
	 * 1.正式环境，必须登录，无需传递参数
	 * 2.测试环境下，没有微信登录获取，需要get方式提交个人账号,才能获取信息
	 * @param [type] account_id 个人账号
	 * @return
	 * success:{"result": 0, "operation": "GetMyInfo", "data": {"id": 5841, "photo": "http://wx.qlogo.cn/mmopen/vi_32/Jstogu0jaTGvHficoHwNh5Tpju1zba2ylIMgHibfCmEyZiaA92qjtP8hQb8EYmSXXibDDD4PV2sLMfXoSPc12dhRsg/0", "cards": 0 } }
	 * fail: {"result":1,"operation":"GetMyInfo","data":""}
	 */
	public function GetMyInfo(){
		header('Access-Control-Allow-Origin:*');
		// 响应类型
		header('Access-Control-Allow-Methods:POST');
		// 响应头设置
		header('Access-Control-Allow-Headers:x-requested-with,content-type');
		header('Access-Control-Allow-Methods:GET');
		$id= Session::get('member_id');
		if(!$id){
			$id=isset($_GET['account_id'])?($_GET['account_id']+0):0;
		}
		$result['result']=1;
		$result['operation']='GetMyInfo';
		$result['data']='';
		if($id){
			$member=$this->IsMember($id,'id,game_id,photo,cards,nickname,room_id,'.$this->filed);
			if(!$member)return json_encode($result);
			$member->nickname=@base64_decode($member->nickname);
			$room = model('room')->where(['id'=>$member->room_id])->field('room_number')->find();
			if($room){
				$member->room_number=$room->room_number;
			}
			if($member){
				$result['result']=0;
				$result['data']=$member;
			}
		}
		return json_encode($result);
	}
	/**
	 * 创建房间，成功后。初始化自己的状态account_status=0 online_status=1 room_id=room->id account_score=0 （积分清零）   jointime=time()   sort=1（ 座位设为1）
	 * 返回 当前局数(game_num) 总局数(playcount)  玩法 (game_type)
	 * room_status 房间游戏状态 0：准备好  1：发牌  2：
	 * islock   准备好的（坐下）人员是否已经满的状态  0：为锁定  1 锁定；坐下时，判断准备好的是否>=4，如过满则islock=1,站起时则islock=0;
	 *  @param
	 * $postData=[
	 *     'account_id'=>,//会员id
	 *     'operation'=>'CreateRoom',
	 *     'data'=>[
	 *                 'ticket_type'=>1,//钻石模式,//1：1:50金币15分钟 2:100金币30分钟  3:150金币 45分钟  4:200金币 1小时
	 *                 'game_type'=>,//玩法  1：按时间结算
	 *             ],
	 *     ]
	 * @return
     * scucess:{"operation": "CreateRoom", "result": 0, "result_message": "创建房间", "data": {"room_id": "375583", "room_number": "1b0q2r50vlg", "starttime": 13855221111, "end_time": 13955221111, "game_type": 1 }, "players": [{"id": 5840, "nickname": "丑男来了", "photo": "http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJhibVwX1zg8ibgPxfzPy03eEbwlCiamRDyrD34ic90Igm0YEpTReiaeS2dM4FicopKIxXjuFBufiaRB4e5A/0", "online_status": 1, "account_status": 0, "account_score": 0, "sort": 0, "jointime": 1513824411, "cards_info": [] } ] }
	 * fail:$result=['result'=>1,'result_message'=>'创建失败']
	 *     $result=['result'=>1,'result_message'=>'无效信息']
	 */
	public function CreateRoom(){
		$dataPost=$this->GetPost();
		if(!$dataPost){
			return $this->ErrorInfo('CreateRoom','无效信息');
		}
		//判断是否是会员
		$memberInfo = $this->IsMember($dataPost['account_id'],"nickname,id,{$this->filed}");
		if(!$memberInfo){
			return $this->ErrorInfo('CreateRoom','无效信息');
		}
     //判断钻石是否足够最低场次的，默认为1，最少需要开房间的钻石
        $ticket_type=1;
        $cards=$this->GetGameCards();
        if(array_key_exists($ticket_type,$cards)){
            if($memberInfo[$this->filed] > $cards[$ticket_type]){
                //创建房间
                $result = $this->RoomCreate($dataPost);
                //当前房间的所有用户信息
                $players=$this->GetCteatePlayerInfo($result['data']['room_id']);
                $result['players']=$players;
                // Log::record($result);
                return json_encode($result);  //开房成功
            }
        }
		return $this->ErrorInfo('CreateRoom','钻石不足');
	}
	/**
	 * 第一次点链接进入房间，更新自己状态account_status=0 online_status=1 jointime  room_id，
     * 第二次点击进入则指更新 online_status=1  jointime
	 *  返回申请加入房间的信息 当前局数  总局数 玩法 玩家:id 昵称 头像  积分 account_status 列表返回加入成功。
	 *  房间内准备好的人大于等于4人，锁定房间，但是进入房间的人可以围观
	 *  account_status（自己的游戏状态） 0：已进入   1：围观（同一房间里面，只要不是坐下，都属于围观）  2：坐下 3：发牌    8：游戏结束
	 *  room_status（房间状态） 0：待开始 2：打牌中  8：游戏结束
	 *  游戏总次数玩完，再次进入则会直接返回战绩列表
	 * @param
	 * $postData=[
	 *     'account_id'=>,//会员id
	 *     'operation'=>'PrepareJoinRoom',
	 *     'data'=>['room_number'=>],//房间号
	 *     ]
	 * ]
	 * @return 如果游戏没有结束则返回
	 * success: {"result": 0, "account_id": 5841, "operation": "PrepareJoinRoom", "players": [{"id": 5841, "nickname": "休闲时间", "photo": "http://wx.qlogo.cn/mmopen/vi_32/Jstogu0jaTGvHficoHwNh5Tpju1zba2ylIMgHibfCmEyZiaA92qjtP8hQb8EYmSXXibDDD4PV2sLMfXoSPc12dhRsg/0", "online_status": 1, "account_status": 0, "account_score": 240, "sort": null, "jointime": 1513763234, "cards_info": [] } ], "data": {"room_status": 2, "room_number": "3206944", "playcount": 10, "game_num": 7, "banker_mode": 2, "game_type": 5, "ticket_type": 1 }, "result_message": "围观"}
	 *
	 * faile: ['result'=>1,'operation'=>'PrepareJoinRoom','result_message'=>'房间人数已满！']
	 *     ['result'=>1,'operation'=>'PrepareJoinRoom','result_message'=>'无效信息']
     *
     *
	 * @return 如果游戏结束则返回战绩列表
	 *  success:  {"result": 0, "account_id": 5841, "operation": "GameOver", "data": [{"nickname": "休闲时间", "photo": "http://wx.qlogo.cn/mmopen/vi_32/Jstogu0jaTGvHficoHwNh5Tpju1zba2ylIMgHibfCmEyZiaA92qjtP8hQb8EYmSXXibDDD4PV2sLMfXoSPc12dhRsg/0", "score": 240 }, {"nickname": "丑男来了", "photo": "http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJhibVwX1zg8ibgPxfzPy03eEbwlCiamRDyrD34ic90Igm0YEpTReiaeS2dM4FicopKIxXjuFBufiaRB4e5A/0", "score": -80 } ] }
	 *  faile: {"result": 1, "operation": "GameOver", "result_message": "游戏结束"}
	 */
	public function PrepareJoinRoom(){
		$dataPost=$this->GetPost('PrepareJoinRoom');
		if(!$dataPost){
			return $this->ErrorInfo('PrepareJoinRoom','无效信息');
		}
		//1. 判断是否是会员
		$member = $this->IsMember($dataPost['account_id'],'id,room_id,nickname,photo');
		if(!$member){
			return $this->ErrorInfo('PrepareJoinRoom','无效信息');
		}
		//2. 判断房间是否存在
		$room=$this->RoomIsExist($dataPost);
		$detail=Db::table('t_historyscore')->where(['account_id' =>$dataPost['account_id'],'room_id'=>$room->id])->find();
		if(!$room){
			return $this->ErrorInfo('PrepareJoinRoom','无效信息');
		}
        //3. 判断房间是否已经结束
		if($room->end_time<=time() || $room->room_status==3){//游戏已经结束返回游戏战绩,游戏结束必须是时间到期了而且当前房间状态必须处于已结束
          return $this->GameOver($room->id);
		}
		// 4.初始化自己进入房间后的状态
        $two_in=false;
		if($member->room_id==$room->id){//第二次进入,有可能是掉线了的人，进来,直接推送所有数据给客户端
			$data=['online_status'=>1,'jointime'=>time()];
            $two_in=true;
		}else{//第一次进入
			$data=['room_id'=>$room->id,'online_status'=>1,'account_status'=>0,'jointime'=>time(),'sort'=>null,'game_id'=>7];
		}
		$this->UpdateMemberById($data,$member->id);
		// 5. 获取房间内在线的或者离线后台玩的所有人的id,nickname,jointime
		$players=$this->GetCteatePlayerInfo($room->id);

		//第二次进入的人直接推送gamestart信息给他们
        if($two_in && $room->room_status>=2){
            //打牌者
            $players=$this->GetOlinePlayerInfo($room->id,'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
            //围观者
            $memberInRoom=$this->GetAllMemeberIdAtRoom($room->id);
            $weiGuanMemberInfo=$memberInRoom['weiGuanMemberInfo'];
            foreach ($players as $player) {
                $obj=new \StdClass();
                $obj->id=$player['id'];
                $obj->sort=$player['sort'];
                $obj->nickname=$player['nickname'];
                $obj->photo=$player['photo'];
                $obj->online_status=$player['online_status'];
                $obj->data=$player['cards_info'];
                $obj->isspecial='false';
                $obj->score=$player[$this->filed];
                $cards_info[]=$obj;
                unset($obj);
            }
            $result['result']=0;
            $result['operation'] = "GameStart";
            $result['players']=$cards_info;
            $result['huplayers']=-1;
            $result['weiplayers']=$weiGuanMemberInfo;
            $result['result_message'] = "断线重连推送";
            $result['type'] = 10;  //断线重连
            $result['room_id'] = $room->id;
            return json_encode($result);


        }
        $memberInRoom=$this->GetAllMemeberIdAtRoom($room->id);
        $players=$memberInRoom['allReadyMemberInfo'];



        $fangzhu = $this->IsMember($room['account_id'],'id,nickname,game_id');

		// 6. 返回进房询问结果
		$result['result'] = 0;
		$result['account_id'] = $fangzhu['id'];
		$result['nickname'] = @base64_decode($fangzhu['nickname']);
		$result['mynickname'] = @base64_decode($member['nickname']);
		$result['myphoto'] = $member['photo'];
		$result['myaccount_id'] = $member['id'];
		$result['operation'] = "PrepareJoinRoom";
		$result['players'] = $players;// 选手信息
		// 房间的的游戏信息
		$result['data']['account_id']=$room->account_id;
		$result['data']['room_id'] = $room->id;
		$result['data']['room_status'] = $room->room_status;
		$result['data']['roomStatus']=$room->roomStatus;
		$result['data']['room_number'] = $room->room_number;
        $result['data']['starttime'] = $room->starttime;
        $result['data']['end_time']=$room->end_time;
		$result['data']['game_num']=$room->game_num;
		$result['data']['game_type']=$room->game_type;
		$result['data']['ticket_type'] = $room->ticket_type;
		$result['result_message'] = "进入成功";
		return json_encode($result);
	}
	/**
	 * 坐下:准备好开始游戏， 更新 online_status=1  account_status=2 account_score  score_board 如果房间没用房主，则坐下的人成为房主
	 * 返回坐下的信息 当前局数  总局数 玩法 玩家:id 昵称 头像  积分 account_status 列表返回坐下成功。
	 * workman 发消息给房主，要求开始
	 *@param
	 * dataPost=[
	 *     'account_id'=>,//会员账号
	 *     'operation'=>'SitDown',
	 *     'data'=>[
	 *         'room_id'=>,//房间id
	 *         'sort'=>//座位 （1  2  3  4）
	 *     ]
	 * ]{"account_id":5841,"operation":"SitDown","data":{"room_id":375801,"sort":1}}
	 * @return
	 * successs: {"result": 0, "operation": "SitDown", "data": {"total_num": 20, "room_id": 375561, "room_number": "9977070", "room_status": 2, "game_num": 6 }, "players": [{"id": 6695, "nickname": "杰仔", "photo": "http://wx.qlogo.cn/mmopen/vi_32/Ff0KhcfAB9oesIx1fu869HVVAicoiaNq5t3vCFNT6cfxKdVBKkpVplnY38KpxSmvp3NKazulhlxOkicpNWNgI13nQ/0", "online_status": 0, "account_status": 3, "account_score": 350, "sort": null, "jointime": null, "cards_info": ["D7", "A4", "C3", "C11", "A3", "A10", "A12", "B3", "B2", "D1", "C1", "C9", "B10"] }, {"id": 5840, "nickname": "丑男来了", "photo": "http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJhibVwX1zg8ibgPxfzPy03eEbwlCiamRDyrD34ic90Igm0YEpTReiaeS2dM4FicopKIxXjuFBufiaRB4e5A/0", "online_status": 1, "account_status": 2, "account_score": 0, "sort": 1, "jointime": 1513757404, "cards_info": [] } ], "result_message": "坐下，准备好！"}
	 * faile: ['result'=>1,'operation'=>'SitDown','result_message'=>'房间人数已满！']
	 *    ['result'=>1,'operation'=>'SitDown','result_message'=>'无效信息']
	 */
	public function SitDown(){
		$dataPost=$this->GetPost('SitDown');
		if(!$dataPost or !isset($dataPost['data']['sort'])){
			return $this->ErrorInfo('SitDown','无效信息');
		}
		//1.座位号错误
		if($dataPost['data']['sort']<0 or $dataPost['data']['sort']>4){
			return $this->ErrorInfo('SitDown','座位号错误');
		}
		//2.判断是否是会员
		$member = $this->IsMember($dataPost['account_id'],"id,{$this->filed},room_id,nickname,photo");
		if(!$member){
			return $this->ErrorInfo('SitDown','无效信息2');
		}
		//3.判断房间是否存在,
		$room=$this->RoomIsExist($dataPost);
		if(!$room){
			return $this->ErrorInfo('SitDown','无效信息3');
		}

//		//判断是否有人坐下，第一个人坐下就是房主，因为他消耗的钻石
//
		//如果房间没有房主，则成为房主,房主的座位号为1
		if(empty($room->account_id)){
			$this->UpdateRoomById(['account_id'=>$member->id],$room->id);
            $room['account_id']=$member->id;
           // $dataPost['data']['sort']=1;
		}else{
            if($room->account_id==$dataPost['account_id']){
             //   $dataPost['data']['sort']=1;
            }
        }



		// 3. 房间是否锁定（锁定：代表已经有4个人已经坐下了），返回false，否则取得准备好人员的sort的信息
		$allmember=$this->RoomIsLock($room->id,'id,sort');
		if($allmember===false){
			return $this->ErrorInfo('SitDown','房间已经坐满！');
		}
		// 4. 验证座位号是否被占用
		$sorts=array_column($allmember,'sort');
		if(in_array($dataPost['data']['sort'], $sorts)){
			//座位号错误
			return $this->ErrorInfo('SitDown','此座位号已被占用');
		}

		//4.5   坐下需要扣除钻石
        $cards=$this->GetGameCards();
        if(array_key_exists($room->ticket_type,$cards)) {
            if ($member[$this->filed] >= $cards[$room->ticket_type]) {
                $member[$this->filed]=$member[$this->filed]- $cards[$room->ticket_type];
                $member->save();
            }else{
                $shengyuzuanshi=$cards[$room->ticket_type]-$member[$this->filed] ;
                return $this->ErrorInfo('SitDown','钻石还差'.$shengyuzuanshi.'个，请先充值');
            }
        }else{
            return $this->ErrorInfo('SitDown','房间数据异常');
        }

		// 6. 更新个人状态
		$data=['online_status'=>1, 'score_board'=>0, 'account_score'=>0, 'account_status'=>2, 'sort'=>$dataPost['data']['sort'], ];
		if($dataPost['data']['room_id'] != $member->room_id){
			$data['room_id']=$room->id;
		}
		$this->UpdateMemberById($data,$member->id);
		//判断房间是否已经坐了4个人，如果坐了4个人，直接锁定房间,打开开始按钮
        $allmember=$this->RoomIsLock($room->id,'id,sort');
        if($allmember===false){
            //可以显示开始游戏了
            $room['roomStatus']=1;
            $this->UpdateRoomById(array('roomStatus'=>1,'room_status'=>1),$room->id);
        }else{
           if(count($allmember)<=1){
               //更改房主
               $this->UpdateRoomById(['account_id'=>$member->id],$room->id);
               $this->UpdateMemberById(['sort'=>1,'is_banker'=>1],$member->id);
           }

        }
		// 7. 获取房间内在线的或者离线后台玩的所有人的id,nickname,jointime,sort
		$players=$this->GetCteatePlayerInfo($room->id);

		// 返回准备好的信息
		$result['result'] = 0;
		$result['operation'] = "SitDown";
        $result['data']['end_time'] = $room['end_time'];
		$result['data']['account_id'] = $room['account_id'];
		$result['data']['roomStatus'] = $room['roomStatus'];//roomStatus=1则显示开始按钮
		$result['data']['room_id'] = $room['id'];
		$result['data']['room_number'] = $room['room_number'];
		$result['data']['game_num'] = $room['game_num'];
		$result['players']=$players;
		$result['myself']['account_id']=$member->id;
		$result['myself']['nickname']=@base64_decode($member->nickname);
		$result['myself']['photo']=$member->photo;
        $result['myself']['sheng']=100;
        $result['myself']['ping']=100;
        $result['myself']['tao']=100;
        $result['myself']['sort']=$data['sort'];
		$result['result_message'] = "坐下，准备好！";
		return json_encode($result);
	}
	/**
	 * 站起：如果游戏结束，状态为 8时，可以站起，否则不可以。如果房主站起，则将房主转给下一个人,没有其他人则account_id=0
	 * 站起后更新 account_status=0 sort=null 如果 t_room 中islock=1 则改为0
	 * @param dataPost=[
	 *     'account_id'=>,//会员账号
	 *     'operation'=>'StandUp',
	 *     'data'=>[
	 *         'room_id'=>,//房间id
	 *     ]
	 * ]
	 * @return
	 * success:{"result": 0, "operation": "StandUp", "data": {"total_num": 20, "room_id": 375561, "room_number": "9977070", "room_status": 2, "game_num": 6 }, "players": [{"id": 6695, "nickname": "杰仔", "photo": "http://wx.qlogo.cn/mmopen/vi_32/Ff0KhcfAB9oesIx1fu869HVVAicoiaNq5t3vCFNT6cfxKdVBKkpVplnY38KpxSmvp3NKazulhlxOkicpNWNgI13nQ/0", "online_status": 0, "account_status": 3, "account_score": 350, "sort": null, "jointime": null, "cards_info": ["D7", "A4", "C3", "C11", "A3", "A10", "A12", "B3", "B2", "D1", "C1", "C9", "B10"] }, {"id": 6737, "nickname": "小磊", "photo": "http://wx.qlogo.cn/mmopen/vi_32/AR6UTBhqOpOkYvEOkQUEgUS3JZetXcF0nDBeJ10gfxNDD2tHTAx1X54eRY6AJOFhXaPT0xhGD5Cx3Qg5mgU7EQ/0", "online_status": 1, "account_status": 3, "account_score": -85, "sort": null, "jointime": null, "cards_info": ["C8", "B12", "B8", "B1", "C2", "B7", "C5", "B13", "D8", "A13", "B6", "B9", "D13"] } ], "result_message": "站起成功！"}
	 * fail:   {"result": 1, "operation": "StandUp", "result_message": "无效信息"}
	 * 		{"result": 1, "operation": "StandUp", "result_message": "游戏未结束，不能站起！"}
	 */
	public function StandUp(){
		$dataPost=$this->GetPost('StandUp');
		if(!$dataPost){
			return $this->ErrorInfo('StandUp','无效信息');
		}
		//1.判断是否是会员
		$member = $this->IsMember($dataPost['account_id'],'id,account_status');
		if((!$member) or $member->account_status<2 ){
			return $this->ErrorInfo('StandUp','无效信息');
		}
		//2.判断房间是否存在,是否锁定
		$room=$this->RoomIsExist($dataPost);
		if(!$room){
			return $this->ErrorInfo('StandUp','房间不存在');
		}
		//3.判断游戏是否结束，否则不能站起
		if($member->account_status <8 ){
			return $this->ErrorInfo('StandUp','游戏未结束，不能站起！');
		}
		//4.修改自己的状态
		$this->UpdateMemberById(['account_status'=>0,'sort'=>null],$member->id);
		// 5. 如果房间是锁定的，则修改房间的锁定状态
		$data=[];
		$allMemberInRoom=$this->GetAllMemeberIdAtRoom($room->id);
		if($room->islock==1){
			$data['islock']=0;
		}
		//6. 如果是房主站起，则将房间所有权转让给下一位游戏者
		if($room->account_id==$member->id){
			$inGameMember=$allMemberInRoom['inGameMember'];
			if(isset($inGameMember[$member->id])){
				unset($inGameMember[$member->id]);
			}
			if(count($inGameMember)>0){
				$inGameMember=array_values($inGameMember);
				$data['account_id']=$inGameMember[0]['id'];
			}else{
				$data['account_id']=null;
			}
		}
		if(!empty($data))$this->UpdateRoomById($data,$room->id);
		$players=$this->GetOlinePlayerInfo($room->id);
		// 7.返回站起成功
		$result['result'] = 0;
		$result['operation'] = "StandUp";
		$result['data']['total_num'] = $room['total_num'];
		$result['data']['room_id'] = $room['id'];
		$result['data']['room_number'] = $room['room_number'];
		$result['data']['room_status'] = $room['room_status'];
		$result['data']['game_num'] = $room['game_num'];
		$result['players']=$players;
		$result['result_message'] = "站起成功！";
		return json_encode($result);
	}
	/**
	 * 获得所有玩家信息
	 * @param
	 * dataPost=[
	 *     'account_id'=>,//会员账号
     *     'json'=>1,
	 *     'data'=>[
	 *         'room_id'=>,//房间id
	 *     ]
	 * ]
	 * @return
	 *sucssee:{"result": 0, "operation": "AllGamerInfo", "data": [{"id": 6695, "nickname": "杰仔", "cards_info": ["D7", "A4", "C3", "C11", "A3", "A10", "A12", "B3", "B2", "D1", "C1", "C9", "B10"], "account_status": 3, "online_status": 1, "sort": 1, "jointime": 1513581353 }, {"id": 5840, "nickname": "丑男来了", "cards_info": [], "account_status": 2, "online_status": 1, "sort": null, "jointime": null } ], "result_message": "所有玩家状态"}
	 *fail:['result'=>1,'operation'=>'AllGamerInfo','result_message'=>'无效信息']
	 */
	public function AllGamerInfo(){
		$dataPost=$this->GetPost('AllGamerInfo');
		if(!$dataPost){
			return $this->ErrorInfo('AllGamerInfo','无效信息');
		}
		//判断是否是会员
		$member = $this->IsMember($dataPost['account_id'],'*');
		if(!$member){
			return $this->ErrorInfo('AllGamerInfo','无效信息');
		}
		$room = model('room')->where(array('id' => $dataPost['data']['room_id']))->find();
		if(!$room){
			return $this->ErrorInfo('AllGamerInfo','房间不存在');
		}
		// 取得在房间内所有在线人员的信息，判断是否在线online_status
		$id=$room->id;
		$allMemberInRoom = Db::query("select id,nickname,cards_info,account_status,online_status,sort,jointime,{$this->filed} from t_member where room_id =$id order by sort asc,jointime asc");
		foreach ($allMemberInRoom as $key => $val) {
			$allMemberInRoom[$key]['nickname']=@base64_decode($val['nickname']);
			$allMemberInRoom[$key]['cards_info']=empty($val['cards_info'])? array() : @unserialize($val['cards_info']);
		}
		$result['result'] = 0;
		$result['room_id'] = $dataPost['data']['room_id'];
		$result['room_number'] = $room['room_number'];
		$result['account_id'] =$room['account_id'];
		$result['operation'] = "AllGamerInfo";
		$result['data'] = $allMemberInRoom;
		$result['result_message'] = "所有玩家状态";
		 return json_encode($result);


	}
	/**
	 * 游戏第一局必须是房主点击开始按钮，游戏开始：发牌(只要有四人准备好了，且房主点击开始了才发牌并保存到cards_info字段里)修改starttime=time()，将牌信息返回给相应的人
	 * @param
	 * dataPost=[
	 *     'account_id'=>,//会员账号
	 *     'operation'=>'GameStart',
	 *     'data'=>[
	 *         'room_id'=>,//房间id
	 *     ]
	 * ]
	 * @return
	 * success: {"result": 0, "operation": "GameStart", "data": {"account_id": 6695, "room_id": 375561, "account_status": 2, "online_status": 0, "limit_time": 60 }, "cards_info": [{"account_id": 6737 }, {"data": ["B3", "D9", "D3", "A3", "D1", "D4", "B9", "D6", "C12", "B11", "B12", "B8", "A10"] }, {"prompt": ["乌龙", "乌龙", "乌龙"] }, {"isspecial": "false"}, {"score": 0 }, {"account_id": 6738 }, {"data": ["B5", "A11", "C9", "A9", "D13", "B4", "A1", "B7", "A12", "D10", "C2", "A13", "B10"] }, {"prompt": ["乌龙", "乌龙", "乌龙"] }, {"isspecial": "false"}, {"score": 0 } ], "result_message": "游戏开始了"}
	 * fail:
	 */
	public function GameStart(){
	    /*****1.接收验证数据*******/
		$dataPost=$this->GetPost('GameStart');
		if(!$dataPost){
			return $this->ErrorInfo('GameStart','无效信息');
		}
		//判断是否是会员
		$member = $this->IsMember($dataPost['account_id'],'id,account_status,online_status');
		if(!$member){
			return $this->ErrorInfo('GameStart','无效信息');
		}
		// 判断房间是否存在
		$room = model('room')->where(array('id' => $dataPost['data']['room_id']))->find();
		if(!$room){
			return $this->ErrorInfo('GameStart','房间不存在');
		}
		//判断是否是房主点击的开始
		if($room->account_id != $dataPost['account_id']){
			return $this->ErrorInfo('GameStart','您不是房主');
		}
		//如果房间状态不等于1（1表示准备好），返回false;
		if($room->room_status !=1){
			return $this->ErrorInfo('GameStart','房间状态不对');
		}
	  /*****2.查询同一房间且符合条件的会员id*******/
		$memberInRoom=$this->GetAllMemeberIdAtRoom($room->id);
		$memberIds=$memberInRoom['memberIds'];//在线的
		$allReadyMember=$memberInRoom['allReadyMember'];

		$allReadyMemberInfo=$memberInRoom['allReadyMemberInfo'];  //打牌的
        $weiGuanMemberInfo=$memberInRoom['weiGuanMemberInfo'];   //围观的

	  /*****3.初始化返回结果*******/
		$result['result'] = 0;
		$result['operation'] = "GameStart";
		$result['data']['account_id'] = $member['id'];
		$result['data']['room_id'] =$room->id;
        $result['data']['windarea'] =$room->windarea;
		$result['data']['account_status'] = $member['account_status'];
		$result['data']['online_status'] = $member['online_status'];
	  /*****4.准备好的人数不够，返回没准备好*******/
		if(count($allReadyMember)<4){
			$result['playercount']=count($allReadyMember);
			$result['result_message'] = "人员还没准备好！";
			return json_encode($result);
		}
		/*****5.修改状态*******/
		// 3.3 更新房间状态
		$game_num=$room->game_num +1;
		//roomStatus=2 则不再显示开始按钮  room_status=2   游戏已经开始
		$data=['starttime'=>time(),'game_num' => $game_num, 'room_status' => 2,'roomStatus'=>2];
		$this->UpdateRoomById($data,$room->id);
		//3.4发牌
		$this->Xiangshan->create(count($allReadyMember));
		$paiInfo=$this->Xiangshan->getallcards();
        // 分别保存到会员表的cards_info里，并修改account_status=3 表示已经发牌
        $evpai=$paiInfo['playcards'];
        $allcards_num=count($paiInfo['cards']['yupai']);
		foreach ($allReadyMemberInfo as $key => $val) {
            $key=$key-1;
			$pai=serialize($evpai[$key]);
			$allReadyMemberInfo[$key]['cards_info']=$evpai[$key];
			$this->UpdateMemberById(['cards_info'=>$pai,'account_status'=>3],$val['id']);
			$zhuang[$key]=$val['id'];
		}
        //保存玩家对应座位，
        $this->Xiangshan->zhuang=$zhuang;
        $paiInfo=$this->Xiangshan->getallcards();
        //保存当前所有的牌数据到room表字段里面
        $data=['cardsinfo'=>serialize($paiInfo)];
        $this->UpdateRoomById($data,$room->id);
		$players=$this->GetOlinePlayerInfo($room->id,'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
		$cards_info=[];
		foreach ($players as $player) {
			$obj=new \StdClass();
			$obj->id=$player['id'];
			$obj->sort=$player['sort'];
			$obj->nickname=$player['nickname'];
			$obj->photo=$player['photo'];
			$obj->online_status=$player['online_status'];
			$obj->data=$player['cards_info'];
			$obj->isspecial='false';
			$obj->score=$player[$this->filed];
			$cards_info[]=$obj;
			unset($obj);
		}
		//检测庄家是否能够胡
        $index=0;$hu=-1;
        $zhuangcards=$evpai[$index]['pai'];
        $is_hu=$this->Xiangshan->checkCanHuPai($zhuangcards);
        if ($is_hu!==false) $hu=$index;
		$result['operation'] = "GameStart";
		$result['players']=$cards_info;
		$result['yupai']=$allcards_num;
		$result['huplayers']=$hu;
        $result['weiplayers']=$weiGuanMemberInfo;
        $result['result_message'] = "游戏开始了";
        $result['type'] = 1;  //正常开始
        $result['autoplay'] = $this->Xiangshan->autoplay;
        $result['gameovertimer'] = $this->Xiangshan->gameovertimer;
        $result['timer'] = $this->Xiangshan->timer;
		return json_encode($result);
	}
    /**
     * 游戏自动开始：从第二局，自动发牌给所有在玩牌的人
     * @param
     * dataPost=[
     *     'operation'=>'GameAutoStart',
     *     'data'=>[
     *         'room_id'=>,//房间id
     *     ]
     * ]
     * @return
     * success: {"result": 0, "operation": "GameStart", "data": {"account_id": 6695, "room_id": 375561, "account_status": 2, "online_status": 0, "limit_time": 60 }, "cards_info": [{"account_id": 6737 }, {"data": ["B3", "D9", "D3", "A3", "D1", "D4", "B9", "D6", "C12", "B11", "B12", "B8", "A10"] }, {"prompt": ["乌龙", "乌龙", "乌龙"] }, {"isspecial": "false"}, {"score": 0 }, {"account_id": 6738 }, {"data": ["B5", "A11", "C9", "A9", "D13", "B4", "A1", "B7", "A12", "D10", "C2", "A13", "B10"] }, {"prompt": ["乌龙", "乌龙", "乌龙"] }, {"isspecial": "false"}, {"score": 0 } ], "result_message": "游戏开始了"}
     * fail:
     */
    public function GameAutoStart(){
        $dataPost=$this->GetPost('GameAutoStart');
        if(!$dataPost){
            return $this->ErrorInfo('GameAutoStart','无效信息1');
        }
        //2.判断是否是会员
        $member = $this->IsMember($dataPost['account_id'],"id,{$this->filed},room_id,account_status,online_status");
        if(!$member){
            return $this->ErrorInfo('GameAutoStart','无效信息2');
        }
        //3.判断房间是否存在,
        $room=$this->RoomIsExist($dataPost);
        if(!$room){
            return $this->ErrorInfo('GameAutoStart','无效信息3');
        }else{
            $windarea=$this->RoomWind($room->id);
            if($windarea!=false) $room->windarea=$windarea;
        }
        //4.判断此房间是否已经到期了，本期全部结束
        if($room['end_time']<=time() || $room['room_status']==3){
            return $this->GameOver($room->id);
        }

        //变更庄家,如果上局的庄家有明杠或者暗杠的话，则庄家轮到下一家，上一句谁赢了谁连庄，否则连庄
        $zhuang_account_id=$this->UpdateGamerZhuang($room);
        $member = $this->IsMember($zhuang_account_id,"id,{$this->filed},room_id,account_status,online_status");
        //如果房间没有房主，则成为房主
        if(empty($room->account_id)){
            $this->UpdateRoomById(['account_id'=>$member->id],$room->id);
            $room['account_id']=$member->id;
        }
        /*****2.查询同一房间且符合条件的会员id*******/
        $memberInRoom=$this->GetAllMemeberIdAtRoom($room->id);
        $memberIds=$memberInRoom['memberIds'];//在线的
        $allReadyMember=$memberInRoom['allReadyMember'];

        $allReadyMemberInfo=$memberInRoom['allReadyMemberInfo'];  //打牌的
        $weiGuanMemberInfo=$memberInRoom['weiGuanMemberInfo'];   //围观的

        /*****3.初始化返回结果*******/
        $result['result'] = 0;
        $result['operation'] = "GameStart";
        $result['data']['account_id'] = $member['id'];
        $result['data']['room_id'] =$room->id;
        $result['data']['windarea'] =$room->windarea;
        $result['data']['account_status'] = $member['account_status'];
        $result['data']['online_status'] = $member['online_status'];
        //开始下局发牌之路
        $game_num=$room->game_num +1;
        $data=['starttime'=>time(),'game_num' => $game_num, 'room_status' => 2,'roomStatus'=>2,'fixedid'=>0];
        $this->UpdateRoomById($data,$room->id);
        //4发牌
        $this->Xiangshan->create(count($allReadyMember));
        $paiInfo=$this->Xiangshan->getallcards();
        // 分别保存到会员表的cards_info里，并修改account_status=3 表示已经发牌
        $evpai=$paiInfo['playcards'];
        $allcards_num=count($paiInfo['cards']['yupai']);
        foreach ($allReadyMemberInfo as $key => $val) {
            $key=$key-1;
            $pai=serialize($evpai[$key]);
            $allReadyMemberInfo[$key]['cards_info']=$evpai[$key];
            $this->UpdateMemberById(['cards_info'=>$pai,'account_status'=>3],$val['id']);
            $zhuang[$key]=$val['id'];
        }
        //保存玩家对应座位，
        $this->Xiangshan->zhuang=$zhuang;
        $paiInfo=$this->Xiangshan->getallcards();
        //保存当前所有的牌数据到room表字段里面
        $data=['cardsinfo'=>serialize($paiInfo)];
        $this->UpdateRoomById($data,$room->id);
        $players=$this->GetOlinePlayerInfo($room->id,'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
        $cards_info=[];
        foreach ($players as $player) {
            $obj=new \StdClass();
            $obj->id=$player['id'];
            $obj->sort=$player['sort'];
            $obj->nickname=$player['nickname'];
            $obj->photo=$player['photo'];
            $obj->online_status=$player['online_status'];
            $obj->data=$player['cards_info'];
            $obj->isspecial='false';
            $obj->score=$player[$this->filed];
            $cards_info[]=$obj;
            unset($obj);
        }
        //检测庄家是否能够胡
        $index=0;$hu=-1;
        $zhuangcards=$evpai[$index]['pai'];
        $is_hu=$this->Xiangshan->checkCanHuPai($zhuangcards);
        if ($is_hu!==false) $hu=$index;
        $result['operation'] = "GameStart";
        $result['players']=$cards_info;
        $result['yupai']=$allcards_num;
        $result['huplayers']=$hu;
        $result['weiplayers']=$weiGuanMemberInfo;
        $result['result_message'] = "游戏开始了";
        $result['type'] = 1;  //正常开始
        $result['autoplay'] = $this->Xiangshan->autoplay;
        $result['gameovertimer'] = $this->Xiangshan->gameovertimer;
        $result['timer'] = $this->Xiangshan->timer;
        return json_encode($result);
    }
	/**
	 * 更新所有玩家信息
	 */
	public function UpdateGamerInfo(){
	}
	/**
	 * 离线操作，修改用户状态，并在workman中通知其他人
	 * @param
	 * dataPost=[
	 *     'account_id'=>,//会员账号
	 *     'data'=>[
	 *         'room_id'=>,//房间id
	 *     ]
	 * ]
	 * @return
	 * success:{"result": 0, "operation": "GetOffLine", "data": {"account_id": 6695, "online_status": 1, "account_status": 3 }, "players": {"memberIds": [6737, 6738, 5840 ], "allReadyMember": [], "allInitMember": [5840 ], "allReadyMemberInfo": [], "inGameMember": {"6695": {"id": 6695, "online_status": 0, "account_status": 3 }, "6737": {"id": 6737, "online_status": 1, "account_status": 3 }, "6738": {"id": 6738, "online_status": 1, "account_status": 3 } } }, "result_message": "用户下线"}
	 * falil:  {"result": 1, "operation": "StandUp", "result_message": "无效信息"}
	 */
	public function GetOffLine(){
		$dataPost=$this->GetPost('GetOffLine');
		if(!$dataPost){
			return $this->ErrorInfo('GetOffLine','无效信息');
		}
		//判断是否是会员
		$member = $this->IsMember($dataPost['account_id'],'id,account_status,room_id,sort,'.$this->filed);
		if(!$member){
			return $this->ErrorInfo('GetOffLine','invalid info!');
		}
		// 判断房间是否存在
		$room = model('room')->where(array('id' => $member->room_id))->find();
		if(!$room){
			return $this->ErrorInfo('GetOffLine','room is not exsits!');
		}
		//判断游戏是否开始
        //游戏未开始的时候,清除他的数据，判断他是否已经坐下，如果坐下了就把房费返回给他，不支持断线重连
        if($room->room_status<2){
             //返回房费
            $udata['online_status']=0;
            if($member['sort']>0){
                $cards=$this->GetGameCards();
                if(array_key_exists($room->ticket_type,$cards)) {
                    $udata[$this->filed]=$member[$this->filed]+$cards[$room->ticket_type];
                }
                $udata['sort']=0;
                $udata['room_id']=0;
             }
             $this->UpdateMemberById($udata,$member->id);
            //判断他是不是房主，如果是房主，还要修改room的account_id信息
            if($room['account_id']==$member->id){
             $this->UpdateRoomById(array('account_id'=>0),$room->id);
            }
        }else{
            //此处不清除member表中的room_id 目的是即使掉线了，后台依旧等待180s，支持断线重连
            $this->UpdateMemberById(['online_status'=>0],$member->id);
        }
        $players=$this->GetOlinePlayerInfo($room->id);
		$result['result'] = 0;
        $result['operation'] = "GetOffLine";
        $result['data']['room_id']=$room->id;
        $result['data']['room_status']=$room->room_status;
        $result['data']['account_id'] = $member->id;
        $result['data']['online_status'] = 0;
        $result['data']['gameovertimer'] =$this->Xiangshan->gameovertimer;
        $result['data']['account_status'] = $member->account_status;
        $result['players']=$players;
        $result['result_message'] = "用户下线";
        return json_encode($result);
	}
	/**
	 * 手动打牌：手动打
     * 摸牌（1）打牌（2），吃牌（3），碰牌（4），点杠（5），暗杠（6），弯杠（7），过（8），胡牌（9），荒局（10）
     * @param   $turn   当前转向
     * 摸牌~~~  服务器推送
     *
     * 打牌~~~ $data['index']=0     打牌者id        $data['cur_dpai']=int;  打的牌
     *
     * 吃牌~~~  $data['index']=0    吃牌者id
     *
     * 碰牌~~~ $data['index']=0     碰牌者id
     *
     * 点杠~~~ $data['index']=0     点杠者id
     *
     * 暗杠~~~ $data['index']=0     暗杠者id
     *
     * 弯杠~~~ $data['index']=0     弯杠者id
     *
     * 过       $data['index']=0     过牌者id       因为优先推送给的是杠或者碰，所以如果过的是杠或者碰，就找是否可以吃的，如果过的是吃的，那就正常叫牌
     *          $data['kind']=1     1：吃， 2 碰牌，3 点杠，4 暗杠，5 弯杠,6 吃碰，7 吃杠
     *
     *
     * 胡牌~~~  $data['index']=0   胡牌者id
     *          $data['wintype']=2  2.别人打牌自己胡  3.自己摸牌自己胡 4.杠上开花（点杠） 5.杠上开花（暗杠）  6.杠上开花（弯杠）
     *
    //        $dataPost=[
    //            'room_id'=>375619,        //房间号
    //            'operation'=>'ShowCard',  //牌操作
    //            'action'=>6,              //  操作种类
    //            'account_id'=>0,           //  操作者id
    //            'cur_dpai'=>1              //操作牌
    //            'kind'=>1                  //吃碰杠种类
    //        ];
     *
     * @return [bool] false |  true
     */
	public function PlayerShowCard(){
        $dataPost=$this->GetPost('PlayerShowCard');
        if(!$dataPost || !$dataPost['room_id']){
            return $this->ErrorInfo('PlayerShowCard','无效信息');
        }
        // 判断房间是否存在
        $room = model('room')->where(array('id' => $dataPost['room_id']))->find();
        if(!$room){
            return $this->ErrorInfo('PlayerShowCard','房间不存在');
        }
        //判断是否是会员
        $member = $this->IsMember($dataPost['account_id'],'id,account_status,online_status,sort,room_id');
        if(!$member){
            return $this->ErrorInfo('PlayerShowCard','无效信息');
        }
        if($member->room_id!=$dataPost['room_id']){
            return $this->ErrorInfo('PlayerShowCard','房间不对');
        }
        //寻找room里面cards数据
        $cards = model('room')->where(['id' =>$dataPost['room_id']])->field('cardsinfo')->find();
        $cardsinfo=unserialize($cards['cardsinfo']);
        $data['data']['index']=$member->sort-1;
        $data['data']['cur_dpai']=$dataPost['cur_dpai'];
        $data['data']['wintype']=isset($dataPost['wintype'])?$dataPost['wintype']:0;
        $data['data']['account_id']=$dataPost['account_id'];
        $newdata=$this->cpgchecke($dataPost,$cardsinfo);
        if($newdata!=false){
            $dataPost=$newdata;
            $member = $this->IsMember($dataPost['account_id'],'id,account_status,online_status,sort,room_id');
            if(!$member){
                return $this->ErrorInfo('PlayerShowCard','无效信息');
            }
            if($member->room_id!=$dataPost['room_id']){
                return $this->ErrorInfo('PlayerShowCard','房间不对');
            }
            //寻找room里面cards数据
            $cards = model('room')->where(['id' =>$dataPost['room_id']])->field('cardsinfo')->find();
            $cardsinfo=unserialize($cards['cardsinfo']);
            $data['data']['index']=$member->sort-1;
            $data['data']['cur_dpai']=$dataPost['cur_dpai'];
            $data['data']['wintype']=isset($dataPost['wintype'])?$dataPost['wintype']:0;
            $data['data']['account_id']=$dataPost['account_id'];
            $cardsinfo['windarea']=$room->windarea;
            $this->Xiangshan->setallcards($cardsinfo);
            $result=$this->Xiangshan->actionpai($dataPost['action'],$data['data']);
            $canm=1;
        }else{
            $canm=0;
            //$result = ['msg' => '等待其他人操作', 'type' => 1];
            return $this->ErrorInfo('等待其他人操作','房间不对');
        }
        if($result['type']>0){
            //获得操作结束之后的牌数据，写入room里面
            $allcards= $this->Xiangshan->getallcards();
            $allcar['cardsinfo']=serialize($allcards);
            $this->UpdateRoomById($allcar,$dataPost['room_id']);
        }else{
            return $this->ErrorInfo('ShowCard',$result['msg']);
        }
        $evpai=$allcards['playcards'];
        /*****.查询同一房间且符合条件的会员id*******/
        $memberInRoom=$this->GetAllMemeberIdAtRoom($dataPost['room_id']);
        $memberIds=$memberInRoom['memberIds'];//在线的
        $allReadyMember=$memberInRoom['allReadyMember'];
        $allReadyMemberInfo=$memberInRoom['allReadyMemberInfo'];   //打牌者
        $weiGuanMemberInfo=$memberInRoom['weiGuanMemberInfo'];   //围观者
        //保存每个会员的牌数据
        $dps=[];
        foreach ($allReadyMemberInfo as $key => $val) {
            $keys=$val['sort']-1;
            $pai=serialize($evpai[$keys]);
            $dps['cards_info']=$pai;
            if($canm>0) $dps['is_grab']=0;
            $this->UpdateMemberById($dps,$val['id']);
        }

        //荒局，只有摸牌已经摸不到的时候，才可以确定是荒局，保存本局的状态，返回排行榜（全部为0），等待客户端请求重新开局
        if(isset($result['status']) && $result['action']!=9){
            if($result['status']==1){
                $result['type']=1;
                $result['data']=$this->GetHuangMembersScore($dataPost['room_id']);
                //写入本轮积分到表里面
                foreach ($allReadyMemberInfo as $key => $val) {
                    $current_key=$val['sort']-1;
                    $cards=serialize($evpai[$current_key]);
                    $member_id=$val['id'];
                    $room_id = $dataPost['room_id'];
                    $total_num=1;
                    $is_banker=$val['sort']==1?1:0;
                    $niu_count=0;
                    $scorpe=0;
                    $room_time=time();
                    $createtime=time();
                    $Isql="'{$member_id}','{$room_id}','{$total_num}','{$is_banker}','{$cards}','{$niu_count}','{$scorpe}','{$room_time}','{$createtime}'";
                    $sql = "INSERT INTO t_history (member_id,room_id,total_num,is_banker,cards,niu_count,scorpe,room_time,createtime) VALUES ($Isql)";
                    Db::query($sql);
                    $member_id=$val['id'];
                }
                //保存本轮牌局的结束方式
                $o['overtype']=2;
                $this->UpdateRoomById($o,$dataPost['room_id']);

                $result['result']=0;
                $result['action']=10;
                $result['operation'] = "pull_Huangju";
                //$result['wintype'] =array(['三包',15],['清一色',5],['平胡',2]);
                $result['wintype'] =[];
                $result['wincards'] =[];
                $result['winid'] =[];
                $result['loseid'] =[];
                $result['room_id']= $dataPost['room_id'];
                $players=$this->GetOlinePlayerInfo($dataPost['room_id'],'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
                $cards_info=[];
                foreach ($players as $player) {
                    $obj=new \StdClass();
                    $obj->id=$player['id'];
                    $obj->nickname=$player['nickname'];
                    $obj->cards_info=$player['cards_info'];
                    $obj->score=0;
                    $cards_info[]=$obj;
                    unset($obj);
                }
                $result['players']=$cards_info;
                return json_encode($result);

            }


        }
        //赢局，赢牌保存每个会员的积分数据，保存到排行榜，返回排行榜，等待客户端请求重新开局
        if($result['action']==9){
            if($result['type']>0){
                $zdetails[]=array();
                foreach ($allReadyMemberInfo as $key => $val) {
                    $current_key=$val['sort']-1;
                    $member_id=$val['id'];
                    $room_id = $dataPost['room_id'];
                    $total_num=1;
                    $is_banker=$val['sort']==1?1:0;
                    $niu_count=0;
                    $cards='';
                    // $scorpe=$result['score'][$current_key];
                    $scorpe=0;
                    $chip='';
                    $room_time=time();
                    $createtime=time();
                    $Isql="'{$member_id}','{$room_id}','{$total_num}','{$is_banker}','{$niu_count}','{$scorpe},'{$room_time}','{$createtime}'";
                    //$sql = "INSERT INTO t_history (member_id,room_id,total_num,is_banker,niu_count,scorpe,room_time,createtime) VALUES ($Isql)";
                    //Db::query($sql);
    //                //扣除奖励对应的积分
    //                if($scorpe>0){
    //                    Db('member')->where('id',$member_id)->setInc($this->filed,abs($scorpe));
    //                }else{
    //                    Db('member')->where('id',$member_id)->setDec($this->filed,abs($scorpe));
    //                }
    //                //更新到总的排行榜
    //                $all = model("historyscore")->Field('id,score')->where("room_id =$room_id and account_id={$member_id}")->find();
    //                if($all['id']>0){
    //                    $data['score']=$all['score']+$scorpe;
    //                    model("historyscore")->where("id={$all['id']}")->save($data);
    //                }else{
    //                    $Isql="'{$member_id}','{$room_id}','{$scorpe}','{$createtime}'";
    //                    $sql = "INSERT INTO t_historyscore (account_id,room_id,score,end_time) VALUES ($Isql)";
    //                    Db::query($sql);
    //                }

                    $zdetails[$key]['nickname']=@base64_decode($val['nickname']);
                    $zdetails[$key]['score']=$scorpe;
                    $zdetails[$key]['account_id']=$val['id'];
                }
                $result['data']=$zdetails;
                $result['limit_time']=5;
                $result['room_id']= $dataPost['room_id'];
                $result['account_id']=$member_id;
                //保存本轮牌局的结束方式
                $o['overtype']=3;
                $this->UpdateRoomById($o,$dataPost['room_id']);
                //保存下轮的庄家，谁赢了谁当庄家



                $this->UpdateMemberById(['is_banker'=>1],$result['account_id']);
                $result['result']=0;
                $result['action']=10;
                $result['operation'] = "pull_Win";
                //$result['wintype'] =array(['三包',15],['清一色',5],['平胡',2]);
               // $result['wintype'] =[];
                //$result['wincards'] =[];
                //$result['winid'] =[];
                //$result['loseid'] =[];
                $result['room_id']= $dataPost['room_id'];
                $players=$this->GetOlinePlayerInfo($dataPost['room_id'],'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
                $cards_info=[];
                foreach ($players as $player) {
                    $obj=new \StdClass();
                    $obj->id=$player['id'];
                    $obj->nickname=$player['nickname'];
                    $obj->cards_info=$player['cards_info'];
                    $obj->score=0;
                    $cards_info[]=$obj;
                    unset($obj);
                }
                $result['players']=$cards_info;
                return json_encode($result);
            }else{
                $result['type']=0;
                $result['msg']='赢牌数据错误';
                return json_encode($result);
            }
        }



        $players=$this->GetOlinePlayerInfo($dataPost['room_id'],'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
        $cards_info=[];
        foreach ($players as $player) {
            $obj=new \StdClass();
            $obj->id=$player['id'];
            $obj->sort=$player['sort'];
            $obj->nickname=@base64_decode($player['nickname']);
            $obj->photo=$player['photo'];
            $obj->online_status=$player['online_status'];
            $obj->data=$player['cards_info'];
            $obj->isspecial='false';
            $obj->score=$player[$this->filed];
            $cards_info[]=$obj;
            unset($obj);
        }
        //$result['cards_info']=$cards_info;
        $result['players']=$cards_info;
        $result['weiplayers']=$weiGuanMemberInfo;
        $result['room_id']= $dataPost['room_id'];
        $result['account_id']=$dataPost['account_id'];
        return json_encode($result);

	}
	/**
	 * 修改所有人的
	 */
	public function AutoShowCard(){

	}
	/**
	 * 游戏结束
	 * 1.每一局的游戏结束：如果当前局数<游戏总局数，修改房间状态room_status=0  end_time 修改玩游戏人员的account_status  account_score, 保存每个人的战绩信息到t_history，汇总战绩结果到 t_historyscore 更新房间人员的信息：game_id=0 (这样刷新页面就会)
	 * 1.1 返回本局游戏结果
	 * 2.总局数结束：如果当前局数=游戏总局数, 修改房间的 end_time 修改玩游戏人员的account_status  保存每个人的战绩信息到t_history，汇总战绩结果到 t_historyscore
	 * 2.1 返回游戏结束后的 积分排名
	 */
    public function GameOver($room_id=0){
        $dataPost=$this->GetPost();
        if($room_id>0) $dataPost['room_id']=$room_id;

        if(!$dataPost){
            return $this->ErrorInfo('GameOver','无效信息');
        }
        //判断房间是否存在
        $post['data']['room_id']=$dataPost['room_id'];
        $room = $this->RoomIsExist($post);
        if(!$room){
            return $this->ErrorInfo('GameOver','invalid info!');
        }
         if($room['room_status']<3){
             //保存本轮牌局的结束方式
             $o['overtype']=1;
             $o['roomStatus']=3;
             $o['room_status']=3;
             $this->UpdateRoomById($o,$dataPost['room_id']);
         }
        $memberInRoom=$this->GetAllMemeberIdAtRoom($dataPost['room_id']);
        $allReadyMemberInfo=$memberInRoom['allReadyMemberInfo'];
        $all = Db("historyscore")->Field('id,score')->where("room_id ={$dataPost['room_id']}")->find();
        $cards_info=[];
        foreach ($allReadyMemberInfo as $key => $val) {
            if(!$all){
                $scorpe = Db("history")->where("room_id ={$dataPost['room_id']} and member_id={$val['id']}")->sum('scorpe');
                $createtime=time();
                $Isql="'{$val['id']}','{$dataPost['room_id']}','{$scorpe}','{$createtime}'";
                $sql = "INSERT INTO t_historyscore (account_id,room_id,score,end_time) VALUES ($Isql)";
                Db::query($sql);
                //扣除奖励对应的积分
                if($scorpe>0){
                    Db('member')->where('id',$val['id'])->setInc($this->filed,abs($scorpe));
                }else{
                    Db('member')->where('id',$val['id'])->setDec($this->filed,abs($scorpe));
                }
            }else{
                $scorpe=$all['score'];
            }
            $obj=new \StdClass();
            $obj->id=$val['id'];
            $obj->nickname=$val['nickname'];
            $obj->photo=$val['photo'];
            $obj->score=$scorpe;
            $cards_info[]=$obj;
            unset($obj);
        }
        $times=$this->GetGameNums();
        $result['result']=0;
        $result['starttime']=date('Y-m-d H:i',$room['starttime']);
        $result['ticket_type']=$times[$room['ticket_type']];
        $result['game_id']=7;
        $result['operation'] = "GameOver";
        $result['players']=$cards_info;

        //围观者
        $weiGuanMemberInfo=$memberInRoom['weiGuanMemberInfo'];   //围观者
        $result['weiplayers']=$weiGuanMemberInfo;
        return  json_encode($result);
    }
	//更改庄家，依次类推
    private function UpdateGamerZhuang($room){
        //检测上一局是否流局，如果庄家有明杠或暗杠，则庄家轮到下一家。反之则继续坐庄。如果是谁赢了，就谁坐庄，
        $xiazhuang=false;
        $cardsinfo=unserialize($room->cardsinfo);
        if($room->overtype<3){
            $playcards=$cardsinfo['playcards'];
            if(@$playcards[0]['agangpai'] || @$playcards[0]['mgangpai'] || @$playcards[0]['wgangpai']){
                $xiazhuang=true;
            }
            //更换庄
            if($xiazhuang){
                $all = model("member")->Field('id,sort')->where("room_id ={$room->id}")->select();
                foreach ($all as $k=>$v){
                    $sort=$v['sort']-1;
                    if($sort==0) $sort=4;
                    Db("member")->where("id ={$v['id']}")->update(array('sort'=>$sort));
                }
            }
        }else{
            //赢局
            if($room->fixedid>0){
                $i=1;
                $all = model("member")->Field('id,sort')->where("room_id ={$room->id}")->select();
                foreach ($all as $k=>$v){
                    $i++;
                    if($v['id']==$room->fixedid){
                          $sort=1;
                    }else{
                        $sort=$i=$i>4?4:$i;
                    }
                    Db("member")->where("id ={$v['id']}")->update(array('sort'=>$sort));
                }
            }
        }

        $all = model("member")->Field('id')->where("room_id ={$room->id} and sort=1")->find();
        return $all['id'];
    }
	/**
	 * 取得相应房间人员内的战绩列表
	 * @param [int] $room_id    [房间号]
	 * @param [int] $account_id [操作人员id]
	 * @return array  返回结果
	 */
	private function GetMembersScore($room_id,$account_id=0){
       $details=Db::query("select m.nickname,m.photo,d.score,m.id,m.sort,m.cards_info from t_historyscore as d left join t_member as m on (d.room_id={$room_id} and d.account_id=m.id) where d.room_id={$room_id} order by d.score desc");
        if(empty($details)){
            $details=$this->GetOlinePlayerInfo($room_id,'id,nickname,photo,online_status,account_status,account_score,sort,jointime,cards_info,sort');
        }
        $fdetails=[];
        foreach ($details as $key=> $val) {
            $fdetails[$key]['nickname']=@base64_decode($val['nickname']);
            $fdetails[$key]['score']=@$val['score']?@$val['score']:0;
            $fdetails[$key]['id']=$val['id'];
            $fdetails[$key]['photo']=$val['photo'];
            $fdetails[$key]['sort']=$val['sort'];
            if(isset($val['cards_info'])){
                $fdetails[$key]['cards_info']=empty($val['cards_info'])? array() : @unserialize($val['cards_info']);
            }
        }
        return $fdetails;
	}
	/**
     * 取得相应房间人员内的荒局战绩列表
     * @param [int] $room_id    [房间号]
     * @return array  返回结果
     */
    private function GetHuangMembersScore($room_id){

        $details=$this->GetOlinePlayerInfo($room_id);
        $zdetails=[];
        foreach ($details as $key=> $val) {
            $zdetails[$key]['nickname']=$val['nickname'];
            $zdetails[$key]['score']=0;
            $zdetails[$key]['account_id']=$val['id'];
        }
        return $zdetails;
    }
	/**
	 * 按座位和加入时间排序，获得在线选手以及离线在玩选手的信息
	 * @param [int] $room_id [房间id]
	 */
	private function GetOlinePlayerInfo($room_id,$field=""){
        if($field==''){
            $field='id,nickname,photo,online_status,account_status,account_score,sort,jointime,'.$this->filed;
        }else{
            $field.=','.$this->filed;
        }
		$all = Db::query("select $field from t_member where room_id =$room_id and ( (online_status=1 or account_status>=2) and sort>0 ) order by sort asc ,jointime asc ");
		if(empty($all))$all=[];
		$ret=[];
		foreach ($all as  $val) {
			if(isset($val['nickname'])){
				$val['nickname']=$this->DecodeNickname($val['nickname'],0);
			}
			if(isset($val['cards_info'])){
				$val['cards_info']=empty($val['cards_info'])? array() : @unserialize($val['cards_info']);
			}
			$ret[]=$val;
		}
		return $ret;
	}
    /**
     * 按座位和加入时间排序，获得在线选手以及离线在玩选手的信息
     * @param [int] $room_id [房间id]
     */
    private function GetCteatePlayerInfo($room_id,$field=""){
        if($field==''){
            $field='id,nickname,photo,online_status,account_status,account_score,sort,jointime,'.$this->filed;
        }else{
            $field.=','.$this->filed;
        }
        $all = Db::query("select $field from t_member where room_id =$room_id  and  online_status=1   order by jointime asc ");
        if(empty($all))$all=[];
        $ret=[];
        foreach ($all as  $val) {
            if(isset($val['nickname'])){
                $val['nickname']=$this->DecodeNickname($val['nickname'],0);
            }
            if(isset($val['cards_info'])){
                $val['cards_info']=empty($val['cards_info'])? array() : @unserialize($val['cards_info']);
            }
            $ret[]=$val;
        }
        return $ret;
    }
	/**
	 * 返回同一房间内所有人的id 状态
	 * @param [type] $room_id [房间id]
	 * @return array $ret  [会员id 在线状态 游戏状态]
	 */
	private function GetAllMemeberIdAtRoom($room_id){
		$all = Db::query("select id,online_status,account_status,sort,nickname,photo from t_member where room_id =$room_id order by jointime asc");
		if(empty($all))$all=[];
		
		$memberIds=[];// online_status=1 房间内在线的id
		$allReadyMember=[];// account_status=2的id 无论是否在线，但准备好游戏 人的id
		$allReadyMemberInfo=[];// account_status=2的id 无论是否在线，但准备好游戏 的人的状态信息
		$allInitMember=[];// online_status=1  account_status<2 在线且准备好游戏人的id
		$inGameMember=[];//正在游戏当中
		$weiGuanMember=[];//围观者
		$weiGuanMemberInfo=[];//围观者信息

		foreach ($all as  $val) {
			if(!empty($val['nickname'])){
				$val['nickname']=@base64_decode($val['nickname']);
			}
			// 取出符合online_status=1的id
			if($val['online_status']==1){
				$memberIds[]=$val['id'];
			}
			// account_status=2的id 准备好游戏
			if($val['account_status']>=2 && $val['sort']+0>0){
				$allReadyMember[]=$val['id'];
				$allReadyMemberInfo[$val['sort']]=$val;
			}
			// 取出符合online_status=1  account_status<2 在线且准备好的id
			if($val['online_status']==1 && ($val['account_status'] <2 )){
				$allInitMember[]=$val['id'];
			}
			//取出所有正在游戏的人
			if($val['account_status']>=2){
				$inGameMember[$val['id']]=$val;
			}
			//取出所有围观者人
			if($val['sort']+0<1 &&$val['account_status']==0){
                $weiGuanMember[]=$val['id'];
                $weiGuanMemberInfo[]=$val;
			}

		}
		$ret= [
				'memberIds'=>$memberIds,
				'allReadyMember'=>$allReadyMember,
				'allInitMember'=>$allInitMember,
				'allReadyMemberInfo'=>$allReadyMemberInfo,
				'inGameMember'=>$inGameMember,
				'weiGuanMember'=>$weiGuanMember,
				'weiGuanMemberInfo'=>$weiGuanMemberInfo,
			];
		return $ret;
	}
	private function gamelock($roomid) {
		//锁住不让操作，保证原子性
		$this->gamelockfile = fopen(LOCK_FILE_PATH . $roomid, "w");
		flock($this->gamelockfile, LOCK_EX);
	}
	/**
	 * 游戏中使用的文件锁,解锁
	 * @param $roomid
	 * @return bool
	 */
	private function gameunlock($roomid) {
		//锁住不让操作，保证原子性
		flock($this->gamelockfile, LOCK_UN);
		fclose($this->gamelockfile);
	}
    /**
     * 通过色子修改玩家庄家
     * @param [type] $data   玩家信息
     * @param [type] $zhuang  庄家座位号
     */
    private function UpdateMemberSort($data,$zhuang){
//        if($zhuang>0 && $zhuang<5){
//            foreach($data as $k=>$v){
//                if($v['sort']==1){
//                    $this->UpdateMemberById(['banker'=>0,'sort'=>$zhuang],$v['id']);
//                }
//                elseif($v['sort']==$zhuang){
//                    $this->UpdateMemberById(['banker'=>1,'sort'=>1],$v['id']);
//                }else{
//                    $nobanker[]=$v['id'];
//                }
//            }
//            $this->UpdateMemberInId(['banker'=>0],$nobanker);
//        }
    }
	/**
	 * 通过id修改房间信息
	 * @param [type] $data   修改的数组
	 * @param [type] $roomId 房间id
	 */
	private function UpdateRoomById($data,$roomId){
        Db('room')->where(array('id' => $roomId))->update($data);
	}
	/**
	 * 通过 member 的 id 更新相应字段
	 * @param [type] $data [相应字段数组]
	 * @param [type] $id   [会员id]
	 */
	private function UpdateMemberById($data,$id){
        Db('member')->where('id',$id)->update($data);
	}
    /**
     * 通过 member 的 id数组 更新相应字段
     * @param [type] $data [相应字段数组]
     * @param [type] $id数组   [会员id]
     */
    private function UpdateMemberInId($data,$id){
        $id=implode(',',$id);
        Db('member')->where("id IN($id)")->update($data);
    }
    /**
     * 判断房间是否应该被锁 在线人数大于等于4人就锁定房间
     * @param [type] $id 房间id
     * @param [type] $filed 要查询的字段
     */
    private function RoomWind($id){
        $id+=0;
        $allmember = Db::query("select id from t_member where room_id =$id and is_banker=1");
        $allCount = count($allmember);
        if($allCount >= 4) {
            $room = model('room')->where('id='.$id)->field('windarea')->find();
            $room['windarea']+=1;
            if($room['windarea']>4) $room['windarea']=1;
            $this->UpdateRoomById(['windarea'=>$room['windarea']],$room['id']);
            Db::query("update t_member set is_banker=0 where room_id =$id ");
            return $room['windarea'];
        }
        return false;
    }
	/**
	 * 判断房间是否应该被锁 在线人数大于等于4人就锁定房间
	 * @param [type] $id 房间id
	 * @param [type] $filed 要查询的字段
	 */
	private function RoomIsLock($id,$filed="*"){
		$id+=0;
		$allmember = Db::query("select $filed from t_member where room_id =$id and account_status >=2 and sort>0");
		$allCount = count($allmember);
		if($allCount >= 4){
			$this->LockRoom($id);
			return false;
		}
		return $allmember;
	}
	/**
	 * 判断房间是否存在(可以通过id，或者room_number查询)
	 * @param [array] $data  数组
	 * @return bool false | obj 房间对象
	 */
	private function RoomIsExist($post){
		//判断房间是否存在
		if(isset($post['data']['room_id'])){
			$where=['id' => $post['data']['room_id']];
		}elseif(isset($post['data']['room_number'])){
			$where=['room_number' => $post['data']['room_number']];
		}else{
			return false;
		}
		$room = model('room')->where($where)->find();
		if($room){
			return $room;
		}
		return false;
	}
	/**
	 * 返回id对应人的某些字段数据
	 * @param int $id    [会员账号id]
	 * @param string $field 字段字符串
	 * @return obj $member  会员信息   | bool  false
	 */
	private function IsMember($id,$field='*'){
		//判断是否是会员
		if($field=='*'){
			$member = model('member')->where(['id' =>$id])->find();
		}else{
			$member = model('member')->where(['id' =>$id])->field($field)->find();
		}
		if(!$member)return false; 
		return $member;
	}
	/**
	 * 将昵称解码
	 * @param [type]  $nicknames [昵称]
	 * @param integer $isArray   [是否是数组的标识]
	 */
	private function DecodeNickname($nicknames,$isArray=0){
		if($isArray){
			$result=[];
			foreach ($nicknames as $nickname) {
				$result[]=@base64_decode($nickname);
			}
			return $result;
		}else{
			$result=@base64_decode($nicknames);
			return $result;
		}
	}
	/**
	 * 乐观锁锁定房间，不准再让人坐下，准备开始玩
	 * @param [type] $id [房间id]
	 */
	private function LockRoom($id){
		model('room')->where(['id' => $id])->update(['islock' => 1]);
	}
	/**
	 * 取出提交的数据
	 * @param  post提交的数据
	 * @return array | false 
	 */
	private function GetPost($flag='createroom'){
		$dataPost = json_decode(file_get_contents('php://input'), true);
		if(!isset($dataPost['account_id'])){// POST提交
			//点击链接Get传入参数
			if(isset($_GET['account_id']) && isset($_GET['room_number'])){
				$dataPost['account_id']=$_GET['account_id']+0;
				$dataPost['data']['room_number']=$_GET['room_number'];
			}else{
				return false;
			}
		}
		Log::record(date("Y-m-d H:i:s").' '.$flag.':');
		Log::record($dataPost);
		if(is_array($dataPost)){
			if(isset($dataPost['account_id'])){
				// 开通验证session验证
				if(Session::has('member_id')){
					$member_id = Session::get('member_id');
					if($member_id !=$dataPost['account_id']){
						return false;
					}
				}
				return $dataPost;
			} 
		}
		return false;
	}
	/**
	 * 返回错误信息
	 * @param [type]  $operation  [方法名]
	 * @param [type]  $message    [要返回的信息]
	 * @param integer $res        [返回结果]
	 */
	private function ErrorInfo($operation,$message,$res=1){
		$result['result'] =$res ;
		$result['type'] =0 ;
		$result['operation'] = $operation;
		$result['result_message'] = $message;
		return json_encode($result);
	}
	/**
	 * 获得ticke_type对应的游戏局数参数数组
	 */
	private function GetGameNums()
	{
		return [1=>15,2=>30,3=>45,4=>60];
	}
	/**
	 * 获得ticke_type对应的消耗的金币说参数数组
	 */
	private function GetGameCards(){
		return [1=>50,2=>100,3=>150,4=>200];
	}

    private function Gettype($act,$type){
        foreach($act as $k=>$v){
            if(in_array($type,$v)) return $k;
        }
        return false;
    }
    //吃碰杠校验
    private function cpgchecke($dataPost,$cardsinfo){

        //寻找act数据，做吃碰杠胡校验
        if(in_array($dataPost['action'],[3,4,5,8,9]) &&  $cardsinfo['act']){
            $type=$cardsinfo['act'][$dataPost['account_id']];
            if($dataPost['action']==9){
                 return  $dataPost;
            }elseif($dataPost['action']==8){
                $this->UpdateMemberById(['is_grab'=>-1],$dataPost['account_id']);
                //检测最后谁要操作牌，如果没有的话，就直接啥都不返回
                //判断是否还有人没有操作，如果没有返回不操作
                foreach($cardsinfo['act'] as $k=>$v) {
                    $member=$this->IsMember($k,'is_grab');
                    if($member->is_grab==0) return false;
                }
                //找到操作数最大的那个人，如果没有，就返回摸牌
                $alluser=array_keys($cardsinfo['act']);
                $where['id'] = array('in',$alluser);
                $member = model('member')->where($where)->field('is_grab,id,sort')->order('is_grab desc')->find();
                if($member->is_grab>0){
                    $dataPost['action']=$member->is_grab;
                    $dataPost['index']=$member->sort-1;
                    $dataPost['account_id']=$member->id;
                }else{
                    $dataPost['wintype']=4;
                }
                return $dataPost;
            }elseif($dataPost['action']==5){
                //判断里面是不是有人胡，如果有胡就需要等待了
                $huuser=$this->Gettype($cardsinfo['act'],'hu');
                if($huuser!=false){
                    $member=$this->IsMember($huuser,'is_grab');
                    if($member->is_grab==-1){
                        //代表已经过了，就不需要等待了
                        return  $dataPost;
                    }else{
                        //修改自己的状态，处于等待处理状态
                        $this->UpdateMemberById(['is_grab'=>5],$dataPost['account_id']);
                        return  false;

                    }
                }
                return  $dataPost;
            }elseif($dataPost['action']==4){
                $st=0;
                //判断里面是不是有人胡，如果有胡就需要等待了
                $huuser=$this->Gettype($cardsinfo['act'],'hu');
                if($huuser!=false){
                    $member=$this->IsMember($huuser,'is_grab');
                    if($member->is_grab==-1){

                    }else{
                        //修改自己的状态，处于等待处理状态
                        $this->UpdateMemberById(['is_grab'=>4],$dataPost['account_id']);
                        $st++;
                    }
                }
                //判断里面是不是有人杠，如果杠胡就需要等待了
                $ganguser=$this->Gettype($cardsinfo['act'],'gang');
                if($ganguser!=false){
                    $member=$this->IsMember($ganguser,'is_grab');
                    if($member->is_grab==-1){
                    }else{
                        //修改自己的状态，处于等待处理状态
                        $this->UpdateMemberById(['is_grab'=>4],$dataPost['account_id']);
                        $st++;
                    }
                }
                if($st>0) return false;
                return $dataPost;

            }elseif($dataPost['action']==3){
                //判断里面是不是有人胡，如果有胡就需要等待了

                $st=0;
                $huuser=$this->Gettype($cardsinfo['act'],'hu');
                if($huuser!=false){
                    $member=$this->IsMember($huuser,'is_grab');
                    if($member->is_grab==-1){
                        //代表已经过了，就不需要等待了
                    }else{
                        //修改自己的状态，处于等待处理状态
                        $this->UpdateMemberById(['is_grab'=>3],$dataPost['account_id']);
                        $st++;
                    }
                }
                //判断里面是不是有人杠，如果杠就需要等待了
                $ganguser=$this->Gettype($cardsinfo['act'],'gang');
                if($ganguser!=false){
                    $member=$this->IsMember($ganguser,'is_grab');
                    if($member->is_grab==-1){
                        //代表已经过了，就不需要等待了
                    }else{
                        //修改自己的状态，处于等待处理状态
                        $this->UpdateMemberById(['is_grab'=>3],$dataPost['account_id']);
                        $st++;

                    }
                }
                //判断里面是不是有人碰，如果碰就需要等待了
                $penguser=$this->Gettype($cardsinfo['act'],'peng');
                if($penguser!=false){
                    $member=$this->IsMember($penguser,'is_grab');
                    if($member->is_grab==-1){
                        //代表已经过了，就不需要等待了
                    }else{
                        //修改自己的状态，处于等待处理状态
                        $this->UpdateMemberById(['is_grab'=>3],$dataPost['account_id']);
                        $st++;
                    }
                }
                if($st>0) return false;
                return $dataPost;
            }

            //判断这个人是否属于吃碰杠的那种
            //$this->UpdateMemberById(['is_grab'=>1],$dataPost['account_id']);


        }else{
            return $dataPost;
        }
    }
	/**
	 * 新增一个房间 成功后，扣房卡，更改自己的状态 account_status=0 online_status=1 room_id
	 * @param [type] $post [post提交的数据]
	 * @return [array]$result 返回结果
	 */
	private function RoomCreate($post){
		// 初始化参数
		$result = [];
		$times=$this->GetGameNums();//游戏时间数组
		$card=$this->GetGameCards();//游戏扣的钻石数组

		$ticket_type=$post['data']['ticket_type'];//前端传的房卡索引
		$result['operation'] = "CreateRoom";
		$result['result'] = 1;
		$result['result_message'] = "创建失败";
		if(!array_key_exists($ticket_type, $card) || !array_key_exists($ticket_type, $times) ){
			return $result;
		}
		//房间号 时间戳加6位随机数，随后变成32进制字符串
		$data['room_number'] = time().rand(100000,999999);
		$data['room_number']=base_convert ($data['room_number'],10,32);
		// 添加数据
		$dbroom=model('room');
		$data['account_id'] = $post['account_id'];
		$data['room_cards_num']=$card[$ticket_type];
		$data['ticket_type'] = $ticket_type; 
		$data['end_time']=time()+$times[$ticket_type]*60;
		$data['base_score']=1;
		$data['banker_mode'] = 0; //暂时没用到
		$data['room_status'] = 0;//房间的游戏状态，0未开始，1准备
		$data['game_num']=0;//游戏次数
		$data['islock']=0;//游戏开始后则锁定为1
		$data['game_type']=$post['data']['game_type'];//默认无特殊模式
		$data['starttime']=time();
		$ret=$dbroom->save($data);
		if(!$ret){
			return $result;
		}
		//开房间,更新自己的房间号码，
		$member=Member::get($post['account_id']);
		//$member->cards=($member->cards - $card[$ticket_type]);
		$member->room_id=$dbroom->id;
		$member->online_status=1;
		$member->account_status=0;
		$member->jointime=time();
		$member->sort=0;
		$member->account_score=0;//积分清零
		$member->game_id=7;//象山麻将的id
		$member->save();
		// 返回成功结果
		$result['result'] = 0;
		$result['data']['room_id'] = $dbroom->id;
        $result['data']['nickname']=@base64_decode($member->nickname);
        $result['data']['account_id']=$member->id;
		$result['data']['room_number'] = $data['room_number'];
		$result['data']['starttime'] = $dbroom->starttime;
		$result['data']['end_time']=$dbroom->end_time;
		$result['data']['game_type']=$dbroom->game_type;
		$result['result_message'] = "创建房间";
		return $result;
	}

 }


